package com.eco.fanliapp.admin.controller.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eco.fanliapp.admin.annotation.SysLogAnnotation;
import com.eco.fanliapp.admin.common.BaseController;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.MD5Utils;
import com.eco.fanliapp.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/back/subUser")
public class SubUserController extends BaseController {
    @Autowired
    ISubAccountService subUserService;
    @Autowired
    IRoleInfoService roleService;
    @Autowired
    IMenuInfoService menuInfoService;
    @Autowired
    IRoleInfoMenusService roleInfoMenusService;

    @Autowired
    private IAppCompanyService companyService;

    @Autowired
    private IAdministratorService adminService;

    @Autowired
    private ISubAccountService subAccountService;


    @GetMapping("findRoleList")
    public ServerResponse<List<RoleInfoVO>> findRoleList() {
        Integer userId = getAuthentication().getUserId();
        RoleInfo req = new RoleInfo();
        List<RoleInfoVO> list = new ArrayList<>();
        req.setUserId(userId);
        List<RoleInfo> roleInfos = roleService.selectRoleInfoList(req);
        if(!CollectionUtils.isEmpty(roleInfos))
        for (RoleInfo roleInfo:roleInfos){
            RoleInfoVO roleInfoVO = new RoleInfoVO();
            roleInfoVO.setRoleName(roleInfo.getRoleName());
            roleInfoVO.setUserId(userId);
            roleInfoVO.setId(roleInfo.getId());
            RoleInfoMenus roleInfoMenus = new RoleInfoMenus();
            roleInfoMenus.setRoleinfoId(roleInfo.getId());
            List<RoleInfoMenus> roleInfoMenus1 = roleInfoMenusService.selectRoleInfoMenusList(roleInfoMenus);
            List<Integer> ids = roleInfoMenus1.stream().map(RoleInfoMenus::getMenusId).collect(Collectors.toList());;
            if(!CollectionUtils.isEmpty(ids)){
                List<MenuInfo> menuInfos = menuInfoService.selectMenuInfoByIds(ids);
                roleInfoVO.setMenus(menuInfos);
            }else{
                roleInfoVO.setMenus(null);
            }

            list.add(roleInfoVO);
        }
        return ServerResponse.createBySuccess(list);
    }
    @SysLogAnnotation(value = "删除角色",userType = 2)
    @RequestMapping("delRole")
    public ServerResponse<String> delRole(int id) {
        roleService.deleteRoleInfoByIds(String.valueOf(id));
        return ServerResponse.createBySuccess("删除成功");
    }
    @SysLogAnnotation(value = "删除子账号",userType = 2)
    @RequestMapping("delSubUser")
    public ServerResponse<String> delSubUser(int id) {
        subUserService.deleteSubAccountByIds(String.valueOf(id));
        return ServerResponse.createBySuccess("删除成功");
    }

    @SysLogAnnotation(value = "保存角色",userType = 2)
    @RequestMapping("saveRole")
    public ServerResponse<String> saveRole(RoleInfo roleInfo, @RequestParam List<Integer> ids) {
        Integer userId = getAuthentication().getUserId();
        if (CollectionUtils.isEmpty(ids)) {
            return ServerResponse.createByErrorMessage("权限列表不能为空");
        }
        if (roleInfo.getId()!=null&&roleInfo.getId() != 0) {
            roleInfoMenusService.deleteRoleInfoMenusByIds(String.valueOf(roleInfo.getId()));
            roleService.updateRoleInfo(roleInfo);
        }else{
            roleInfo.setUserId(userId);
            roleService.insertRoleInfo(roleInfo);
        }
        for (Integer id : ids) {
            RoleInfoMenus roleInfoMenus = new RoleInfoMenus();
            roleInfoMenus.setMenusId(id);
            roleInfoMenus.setRoleinfoId(roleInfo.getId());
            roleInfoMenusService.insertRoleInfoMenus(roleInfoMenus);
        }
        return ServerResponse.createBySuccessMessage("保存成功");
    }

    @RequestMapping("getMenuList")
    public ServerResponse getMenuList() {
        List<MenuInfo> menuInfos = menuInfoService.list();
        //处理菜单(子父级关系)
        List<String> menuJsonList = new ArrayList<>();
        for(MenuInfo menu : menuInfos){
            //查询父级菜单
            if(menu.getOrderId() == 0){
                List<MenuInfoVo>  menuChilds = new ArrayList<>();
                //有子菜单
                for(MenuInfo menu2 : menuInfos){
                    if(menu.getId() == menu2.getOrderId()){
                        MenuInfoVo menuInfoVo = new MenuInfoVo();
                        menuInfoVo.setMenuId(menu2.getId());
                        menuInfoVo.setMenuName(menu2.getMenuName());
                        menuInfoVo.setMenuPath(menu2.getMenuUrl());

                        menuChilds.add(menuInfoVo);
                    }
                }
                //构造菜单
                MenuVo vo = new MenuVo();
                vo.setMenuId(menu.getId());
                vo.setMenuName(menu.getMenuName());
                vo.setMenuPath(menu.getMenuUrl());
                vo.setMenuChilds(menuChilds);

                //数据格式组装
                String menuVosonString = JSON.toJSONString(vo);
                menuJsonList.add(menuVosonString);
            }
        }
        //遍历子菜单，确认是否有下级
        List<UserMenuVo> lIst = new ArrayList<>();
        return ServerResponse.createBySuccess(menuJsonList);
//        return ServerResponse.createBySuccess(menuInfoService.selectMenuInfoList(new MenuInfo()));
    }

    @SysLogAnnotation(value = "重置角色",userType = 2)
    @RequestMapping("register")
    public ServerResponse<String> register(SubAccount subUser, int roleId) {
        Integer userId = getAuthentication().getUserId();
        RoleInfo roleInfo = roleService.selectRoleInfoById(roleId);
        if (roleInfo != null) {
            //校验名称是否重复
            QueryWrapper<SubAccount> query = new QueryWrapper<>();
            query.eq("username",subUser.getUsername());
            List<SubAccount> list = subAccountService.list(query);
            if(org.apache.commons.collections.CollectionUtils.isNotEmpty(list)){
                return ServerResponse.createByErrorMessage("用户名username重复");
            }
            subUser.setUserId(userId);
            subUser.setPassword(MD5Utils.createMD5(subUser.getPassword()));
            subUser.setRoleId(roleInfo.getId());
            subUserService.insertSubAccount(subUser);
            return ServerResponse.createBySuccessMessage("添加成功");
        } else {
            return ServerResponse.createByErrorMessage("角色信息错误");
        }
    }

    @SysLogAnnotation(value = "更新角色",userType = 2)
    @RequestMapping("update")
    public ServerResponse<String> update(int roleId, int id, String nickName, String userName, Integer companyId,Integer isVerifyIp) {
        RoleInfo roleInfo = roleService.selectRoleInfoById(roleId);
        SubAccount subUser = subUserService.selectSubAccountById(id);
        if (roleInfo != null && subUser != null) {
            //校验名称是否重复
            if(StringUtils.isEmpty(userName)){
                return ServerResponse.createByErrorMessage("用户名username不能为空!");
            }
           /* QueryWrapper<SubAccount> query = new QueryWrapper<>();
            query.eq("username",userName);
            List<SubAccount> list = subAccountService.list(query);
            if(org.apache.commons.collections.CollectionUtils.isNotEmpty(list)){
                return ServerResponse.createByErrorMessage("用户名username重复");
            }*/


            subUser.setRoleId(roleInfo.getId());
            subUser.setNickName(nickName);
            subUser.setUsername(userName);
            subUser.setCompanyId(companyId);
            subUser.setIsVerifyIp(isVerifyIp);
            subUserService.updateSubAccount(subUser);
            return ServerResponse.createBySuccessMessage("更新用户信息成功");
        } else {
            return ServerResponse.createByErrorMessage("更新用户信息失败");
        }
    }

    @SysLogAnnotation(value = "修改密码",userType = 2)
    @RequestMapping("changePassword")
    public ServerResponse<String> changePassword(String password, int id) {
        SubAccount subUser = subUserService.selectSubAccountById(id);
        if (subUser != null) {
            subUser.setPassword(MD5Utils.createMD5(password));
            subUserService.updateSubAccount(subUser);
            return ServerResponse.createBySuccessMessage("修改密码成功");
        } else {
            return ServerResponse.createByErrorMessage("修改密码失败");
        }

    }
    @RequestMapping("checkUserName")
    public boolean checkUserName(String username) {
        SubAccount subAccount = new SubAccount();
        subAccount.setUsername(username);
        List<SubAccount> subAccounts = subUserService.selectSubAccountList(subAccount);
        Administrator admin = adminService.findByAdministratorName(username);
        if (CollectionUtils.isEmpty(subAccounts)&& StringUtils.isEmpty(admin)) {
            return false;
        }
        return true;
    }

    @RequestMapping("findAllByUserId")
    public ServerResponse findAllByUserId(@RequestParam(defaultValue = "1") Integer pageNum , @RequestParam(defaultValue = "10") Integer pageSize) {
        //Integer userId = getAuthentication().getUserId();
       /* SubAccount subAccount = new SubAccount();
        subAccount.setUserId(userId);
        List<SubAccount> subUsers = subUserService.selectSubAccountList(subAccount);*/
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",2);
        Page<SubAccount> page = new Page(pageNum, pageSize);
        IPage<SubAccount> page1 = subUserService.page(page, queryWrapper);
        List<SubAccount> subUsers = page1.getRecords();
        List<AppCompany> appCompanyList = companyService.list();
        for(SubAccount account : subUsers){
            for (AppCompany appCompany:appCompanyList){
                if(account.getCompanyId() == appCompany.getCompanyId()){
                    account.setCompanyName(appCompany.getCompayName());
                    continue;
                }
            }
        }
        if (CollectionUtils.isEmpty(subUsers)) {
            return ServerResponse.createByErrorMessage("内容为空");
        } else {
            for (SubAccount subAccount1:subUsers) {
                subAccount1.setRole(roleService.selectRoleInfoById(subAccount1.getRoleId()));
            }
            return ServerResponse.createBySuccess(page1);
        }
    }


    /**
     * 旧版本-支持到2.2.1
     * @return
     */
    @RequestMapping(value = "/menu")
    @ResponseBody
    public Object Menth() {
        UserVO userVO = getAuthentication();
        UserMenuVo userMenuVo = new UserMenuVo();
        userMenuVo.setText("返利后台");
        userMenuVo.setGroup(false);
        List<Object> menuInfo = new ArrayList<>();
        if (userVO.getRoleId() != null&&userVO.getRoleId()!=0) {
            RoleInfoMenus req = new RoleInfoMenus();
            req.setRoleinfoId(userVO.getRoleId());
            List<RoleInfoMenus> menuInfos = roleInfoMenusService.selectRoleInfoMenusList(req);
            for (RoleInfoMenus menuInfo1 : menuInfos
            ) {
                MenuInfo menuInfo2 = menuInfoService.selectMenuInfoById(menuInfo1.getMenusId());
                menuInfo.add(JSONObject.parse(menuInfo2.getMenuUrl()));
            }
            userMenuVo.setMainUser(false);
        }else{
            List<MenuInfo> menuInfo2 = menuInfoService.selectMenuInfoList(null);
            for (MenuInfo menuInfo1:menuInfo2){
                if(menuInfo1.getOrderId()==0){
                    menuInfo.add(JSONObject.parse(menuInfo1.getMenuUrl()));
                }
            }
            userMenuVo.setMainUser(true);
            menuInfo.add(JSONObject.parse("{" +
                    "            text: '子账号管理'," +
                    "            link: '/subuser/center/permission'," +
                    "            icon: { type: 'icon', value: 'team' }," +
                    "              shortcutRoot: true," +
                    "            }"));
        }
        userMenuVo.setChildren(menuInfo);

        List<UserMenuVo> lIst = new ArrayList<>();
        lIst.add(userMenuVo);
        return lIst;
    }


    @RequestMapping(value = "/menuNew1")//上线把路由改过来============================
    @ResponseBody
    public ServerResponse MenthNew(){
        //获取当前登陆用户
        UserVO userVO = getAuthentication();
        //获取登陆用户权限下菜单ids
        List<MenuInfo> menuInfos = null;

        if (userVO.getRoleId()==0) {
            //总公司
            menuInfos = menuInfoService.selectMenuInfoList(null);
        }else{
            //非总公司
            RoleInfoMenus req = new RoleInfoMenus();
            req.setRoleinfoId(userVO.getRoleId());
            List<RoleInfoMenus> roleInfoMenus = roleInfoMenusService.selectRoleInfoMenusList(req);
            List<Integer> menuIds = new ArrayList<>();

            for (RoleInfoMenus menuInfo1 : roleInfoMenus) {
                menuIds.add(menuInfo1.getMenusId());
            }

            menuInfos = menuInfoService.selectMenuInfoByIds(menuIds);
        }

        //处理菜单(子父级关系)
        List<String> menuJsonList = new ArrayList<>();
        for(MenuInfo menu : menuInfos){
            //查询父级菜单
            if(menu.getOrderId() == 0){
                List<MenuInfoVo>  menuChilds = new ArrayList<>();
                //有子菜单
                for(MenuInfo menu2 : menuInfos){
                    if(menu.getId() == menu2.getOrderId()){
                        MenuInfoVo menuInfoVo = new MenuInfoVo();
                        menuInfoVo.setMenuId(menu2.getId());
                        menuInfoVo.setMenuName(menu2.getMenuName());
                        menuInfoVo.setMenuPath(menu2.getMenuUrl());

                        menuChilds.add(menuInfoVo);
                    }
                }
                //构造菜单
                MenuVo vo = new MenuVo();
                vo.setMenuId(menu.getId());
                vo.setMenuName(menu.getMenuName());
                vo.setMenuPath(menu.getMenuUrl());
                vo.setMenuChilds(menuChilds);

                //数据格式组装
                String menuVosonString = JSON.toJSONString(vo);
                menuJsonList.add(menuVosonString);
            }
        }
        //遍历子菜单，确认是否有下级
        List<UserMenuVo> lIst = new ArrayList<>();
        return ServerResponse.createBySuccess(menuJsonList);
    }
    @RequestMapping(value = "/selectMenu")
    @ResponseBody
    public ServerResponse selectMenu(Integer orderId) {
        //如果menuId为0查询一级菜单
        QueryWrapper<MenuInfo> query = new QueryWrapper<>();
        query.eq("order_id",orderId);
        List<MenuInfo> list = menuInfoService.list(query);

        return ServerResponse.createBySuccess(list);
    }

    /**
     * 获取登录管理员的菜单权限
     * @return
     */
    @RequestMapping(value = "/menuNew")
    @ResponseBody
    public ServerResponse<List<UserMenuVo>> menuNew() {
        UserVO userVO = getAuthentication();
        UserMenuVo userMenuVo = new UserMenuVo();
        userMenuVo.setText("返利后台");
        userMenuVo.setGroup(false);
        List<Object> menuInfo = new ArrayList<>();
        if (userVO.getRoleId() != null&&userVO.getRoleId()!=0) {
            RoleInfoMenus req = new RoleInfoMenus();
            req.setRoleinfoId(userVO.getRoleId());
            List<RoleInfoMenus> menuInfos = roleInfoMenusService.selectRoleInfoMenusList(req);
            for (RoleInfoMenus menuInfo1 : menuInfos
                    ) {
                MenuInfo menuInfo2 = menuInfoService.selectMenuInfoById(menuInfo1.getMenusId());
                menuInfo.add(menuInfo2);
            }
            userMenuVo.setMainUser(false);
        }else{
            List<MenuInfo> menuInfo2 = menuInfoService.selectMenuInfoList(null);
            for (MenuInfo menuInfo1:menuInfo2){
                if(menuInfo1.getOrderId()==0){
                    menuInfo.add(menuInfo1);
                }
            }
            userMenuVo.setMainUser(true);

        }
        userMenuVo.setChildren(menuInfo);

        List<UserMenuVo> lIst = new ArrayList<>();
        lIst.add(userMenuVo);
        return ServerResponse.createBySuccess(lIst);
    }

    @SysLogAnnotation(value = "创建/更新菜单",userType = 2)
    @PostMapping(value = "/createMenu")
    public ServerResponse createMenu(@RequestBody MenuInfo menuInfo) {
        //判断id是否为空
        Integer id = menuInfo.getId();
        if(id == null){
            //先校验菜单（名称，url)是否合法
            QueryWrapper<MenuInfo> queryWrapper = new QueryWrapper<>();
            String menuName = menuInfo.getMenuName();
            String menuUrl = menuInfo.getMenuUrl();
            queryWrapper.and(wrapper -> wrapper.eq("menu_name",menuName).or().eq("menu_url",menuUrl));
            List<MenuInfo> list = menuInfoService.list(queryWrapper);
            if(CollectionUtils.isEmpty(list)){
                //创建新的菜单
                MenuInfo menuInfo1 = new MenuInfo();
                menuInfo1.setMenuName(menuInfo.getMenuName());
                menuInfo1.setMenuUrl(menuInfo.getMenuUrl());
                menuInfo1.setOrderId(menuInfo.getOrderId());
                menuInfo1.setSortId(menuInfo.getSortId());
                menuInfoService.save(menuInfo1);
            }else{
                return ServerResponse.createByErrorMessage("菜单名称和菜单链接不允许重复");
            }
        }else{
            //更新菜单
            MenuInfo menuInfo2= menuInfoService.getById(menuInfo.getId());
            menuInfo2.setAlias(menuInfo.getAlias());
            menuInfo2.setMenuName(menuInfo.getMenuName());
            menuInfo2.setMenuUrl(menuInfo.getMenuUrl());
            menuInfo2.setOrderId(menuInfo.getOrderId());
            menuInfo2.setSortId(menuInfo.getSortId());
            menuInfoService.updateMenuInfo(menuInfo2);
        }
        return ServerResponse.createBySuccessMessage("操作成功");


    }
}
